#!/usr/bin/env python3
"""
同步球队成员头像
从 users 表同步头像到 team_members 表
"""
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.core.database import SessionLocal
from app.models.user import User
from app.models.team import TeamMember

def sync_member_avatars():
    """同步球队成员头像"""
    db = SessionLocal()
    
    try:
        print("🔄 开始同步球队成员头像...\n")
        
        # 获取所有球队成员
        members = db.query(TeamMember).all()
        total = len(members)
        synced = 0
        cleared = 0
        
        print(f"📊 找到 {total} 个球队成员记录\n")
        
        for member in members:
            # 查找对应的用户
            user = db.query(User).filter(User.id == member.user_id).first()
            
            if not user:
                print(f"  ⚠️  成员 {member.user_name} (ID: {member.user_id}) 找不到对应用户")
                continue
            
            # 比较头像
            if user.avatar != member.avatar:
                old_avatar = member.avatar or "(无)"
                new_avatar = user.avatar or "(无)"
                
                print(f"  🔄 更新成员 {member.user_name} 的头像:")
                print(f"     旧: {old_avatar}")
                print(f"     新: {new_avatar}")
                
                member.avatar = user.avatar
                
                if user.avatar:
                    synced += 1
                else:
                    cleared += 1
            else:
                print(f"  ✅ 成员 {member.user_name} 的头像已是最新")
        
        # 提交更改
        db.commit()
        
        print("\n" + "=" * 60)
        print(f"✅ 同步完成！")
        print(f"   总计: {total} 个成员")
        print(f"   已同步: {synced} 个")
        print(f"   已清空: {cleared} 个")
        print(f"   无需更新: {total - synced - cleared} 个")
        print("=" * 60)
    
    except Exception as e:
        print(f"\n❌ 同步失败: {e}")
        db.rollback()
        raise
    
    finally:
        db.close()

if __name__ == "__main__":
    try:
        sync_member_avatars()
    except Exception as e:
        print(f"\n❌ 执行失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

